//
//  GYXComposeViewController.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/4/5.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit
import SVProgressHUD
/**
 加载视图控制器的时候，如果 XIB 和控制器同名，默认的构造函数，会优先加载 XIB
 */
class GYXComposeViewController: UIViewController {

    
    /// 工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    /// 微博内容
    @IBOutlet weak var textView: GYXTextView!
    /// 发布按钮
    @IBOutlet var sendButton: UIButton!
    
    /// 标题视图
    @IBOutlet var titleLabel: UILabel!
    /// 工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // 添加键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboadChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 开启键盘
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 关闭键盘
        textView.resignFirstResponder()
    }
    
    // MARK: - 事件监听
    @objc private func keyboadChange(note: Notification) {

        guard let rect = (note.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue)?.cgRectValue,
            let duration = (note.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? NSNumber)?.doubleValue else {
                return
        }
        
        let offsetY = view.bounds.height - rect.origin.y
        // 设置toolbar的底部约束
        toolbarBottomCons.constant = offsetY
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    /// 退出
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
    }
   
    /// emoticon键盘
    @objc fileprivate func emoticonKeyboard() {
        print("点击emoticon图标")
    }
    
    
    /// 发布微博
    @IBAction func sendStatus() {
        // 判断文本内容
        guard let text = textView.text else {
            SVProgressHUD.showInfo(withStatus: "文本不能为空")
            return
        }

        // 判断是否有图片
        let image: UIImage? =  UIImage(named: "refreshbg")
        // 发送网络请求
        GYXNetworkManager.shared.postStatus(text: text, image: image) { (json, isSuccess) in
            // 修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            // 设置显示信息
            let message = isSuccess ? "发送成功" : "网络不给力"
            SVProgressHUD.showInfo(withStatus: message)
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    // 恢复指示器默认样式
                    SVProgressHUD.setDefaultStyle(.light)
                    // 关闭当前视图
                    self.close()
                }
            }
        }
        
    }
    
}


// MARK: - UITextViewDelegate
extension GYXComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
    }
}

// MARK: - 视图布局
extension GYXComposeViewController {
    
    /// 初始化视图
    fileprivate func setupUI() {
        
        view.backgroundColor = UIColor.white
        setupToolBar()
        setupNavigationBar()
    }
    
    
    /// 初始化工具条
    private func setupToolBar() {
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            guard let imageName = s["imageName"] else {
                return
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            // 创建按钮
            let btn = UIButton()
            btn.setImage(image, for: .normal)
            btn.setImage(imageHL, for: .highlighted)
            btn.sizeToFit()
            
            // 为按钮添加监听
            if let actionName = s["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            // 添加按钮到items中
            items.append(UIBarButtonItem(customView: btn))
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        // 移除最后一个弹簧
        items.removeLast()
        // 设置toolbar的items
        toolbar.items = items
    }
    
    
    /// 初始化导航条
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        sendButton.isEnabled = false
        navigationItem.titleView = titleLabel
    }
}
